package com.yubest.demo.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @describe: 范围枚举值校验器
 * @author: hweiyu
 * @date: 2020/12/9 16:26
 */
public class RangeEnumValidator implements ConstraintValidator<RangeEnum, Object> {

    private RangeEnum range;

    @Override
    public void initialize(RangeEnum constraintAnnotation) {
        this.range = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        String[] allowableValues = range.allowableValues();
        if (null == o || allowableValues.length == 0) {
            return false;
        }
        String s = o.toString();
        for (String allowableValue : allowableValues) {
            if (s.equals(allowableValue)) {
                return true;
            }
        }
        return false;
    }
}
